package com.mini.utils;

import org.springframework.web.multipart.MultipartFile;
import okhttp3.*;

/**
 * @author 白sa能
 * @className
 * @date Created in 4:16 PM 4/29/21
 * @package com.mini.utils
 * @Description
 */
public class FileUpLoadUtil {
    private static final String UPLOAD_PATH = "http://119.23.218.131:9800/group1/upload";;

    /**
     * 上传文件
     * @param file
     * @return
     */
    public static String upload(MultipartFile file) {
        String result = null;
        try {
            OkHttpClient httpClient = new OkHttpClient();
            MultipartBody multipartBody = new MultipartBody.Builder().
                    setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getOriginalFilename(),
                            RequestBody.create(MediaType.parse("multipart/form-data;charset=utf-8"),
                                    file.getBytes()))
                    .addFormDataPart("output", "json")
                    .build();

            Request request = new Request.Builder()
                    .url(UPLOAD_PATH)
                    .post(multipartBody)
                    .build();

            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                ResponseBody body = response.body();
                if (body != null) {
                    result = body.string();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
}
